home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / email / utils.pyc (.txt) < prev   
Python Compiled Bytecode  |  2009-11-11  |  9KB  |  284 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Miscellaneous utilities.'''
  5. __all__ = [
  6.     'collapse_rfc2231_value',
  7.     'decode_params',
  8.     'decode_rfc2231',
  9.     'encode_rfc2231',
  10.     'formataddr',
  11.     'formatdate',
  12.     'getaddresses',
  13.     'make_msgid',
  14.     'parseaddr',
  15.     'parsedate',
  16.     'parsedate_tz',
  17.     'unquote']
  18. import os
  19. import re
  20. import time
  21. import base64
  22. import random
  23. import socket
  24. import urllib
  25. import warnings
  26. from email._parseaddr import quote
  27. from email._parseaddr import AddressList as _AddressList
  28. from email._parseaddr import mktime_tz
  29. from email._parseaddr import parsedate as _parsedate
  30. from email._parseaddr import parsedate_tz as _parsedate_tz
  31. from quopri import decodestring as _qdecode
  32. from email.encoders import _bencode, _qencode
  33. COMMASPACE = ', '
  34. EMPTYSTRING = ''
  35. UEMPTYSTRING = u''
  36. CRLF = '\r\n'
  37. TICK = "'"
  38. specialsre = re.compile('[][\\\\()<>@,:;".]')
  39. escapesre = re.compile('[][\\\\()"]')
  40.  
  41. def _identity(s):
  42.     return s
  43.  
  44.  
  45. def _bdecode(s):
  46.     if not s:
  47.         return s
  48.     value = base64.decodestring(s)
  49.     if not s.endswith('\n') and value.endswith('\n'):
  50.         return value[:-1]
  51.     return value
  52.  
  53.  
  54. def fix_eols(s):
  55.     '''Replace all line-ending characters with \r
  56. .'''
  57.     s = re.sub('(?<!\\r)\\n', CRLF, s)
  58.     s = re.sub('\\r(?!\\n)', CRLF, s)
  59.     return s
  60.  
  61.  
  62. def formataddr(pair):
  63.     '''The inverse of parseaddr(), this takes a 2-tuple of the form
  64.     (realname, email_address) and returns the string value suitable
  65.     for an RFC 2822 From, To or Cc header.
  66.  
  67.     If the first element of pair is false, then the second element is
  68.     returned unmodified.
  69.     '''
  70.     (name, address) = pair
  71.     if name:
  72.         quotes = ''
  73.         if specialsre.search(name):
  74.             quotes = '"'
  75.         
  76.         name = escapesre.sub('\\\\\\g<0>', name)
  77.         return '%s%s%s <%s>' % (quotes, name, quotes, address)
  78.     return address
  79.  
  80.  
  81. def getaddresses(fieldvalues):
  82.     '''Return a list of (REALNAME, EMAIL) for each fieldvalue.'''
  83.     all = COMMASPACE.join(fieldvalues)
  84.     a = _AddressList(all)
  85.     return a.addresslist
  86.  
  87. ecre = re.compile('\n  =\\?                   # literal =?\n  (?P<charset>[^?]*?)   # non-greedy up to the next ? is the charset\n  \\?                    # literal ?\n  (?P<encoding>[qb])    # either a "q" or a "b", case insensitive\n  \\?                    # literal ?\n  (?P<atom>.*?)         # non-greedy up to the next ?= is the atom\n  \\?=                   # literal ?=\n  ', re.VERBOSE | re.IGNORECASE)
  88.  
  89. def formatdate(timeval = None, localtime = False, usegmt = False):
  90.     '''Returns a date string as specified by RFC 2822, e.g.:
  91.  
  92.     Fri, 09 Nov 2001 01:08:47 -0000
  93.  
  94.     Optional timeval if given is a floating point time value as accepted by
  95.     gmtime() and localtime(), otherwise the current time is used.
  96.  
  97.     Optional localtime is a flag that when True, interprets timeval, and
  98.     returns a date relative to the local timezone instead of UTC, properly
  99.     taking daylight savings time into account.
  100.  
  101.     Optional argument usegmt means that the timezone is written out as
  102.     an ascii string, not numeric one (so "GMT" instead of "+0000"). This
  103.     is needed for HTTP, and is only used when localtime==False.
  104.     '''
  105.     if timeval is None:
  106.         timeval = time.time()
  107.     
  108.     if localtime:
  109.         now = time.localtime(timeval)
  110.         if time.daylight and now[-1]:
  111.             offset = time.altzone
  112.         else:
  113.             offset = time.timezone
  114.         (hours, minutes) = divmod(abs(offset), 3600)
  115.         if offset > 0:
  116.             sign = '-'
  117.         else:
  118.             sign = '+'
  119.         zone = '%s%02d%02d' % (sign, hours, minutes // 60)
  120.     else:
  121.         now = time.gmtime(timeval)
  122.         if usegmt:
  123.             zone = 'GMT'
  124.         else:
  125.             zone = '-0000'
  126.     return '%s, %02d %s %04d %02d:%02d:%02d %s' % ([
  127.         'Mon',
  128.         'Tue',
  129.         'Wed',
  130.         'Thu',
  131.         'Fri',
  132.         'Sat',
  133.         'Sun'][now[6]], now[2], [
  134.         'Jan',
  135.         'Feb',
  136.         'Mar',
  137.         'Apr',
  138.         'May',
  139.         'Jun',
  140.         'Jul',
  141.         'Aug',
  142.         'Sep',
  143.         'Oct',
  144.         'Nov',
  145.         'Dec'][now[1] - 1], now[0], now[3], now[4], now[5], zone)
  146.  
  147.  
  148. def make_msgid(idstring = None):
  149.     '''Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
  150.  
  151.     <20020201195627.33539.96671@nightshade.la.mastaler.com>
  152.  
  153.     Optional idstring if given is a string used to strengthen the
  154.     uniqueness of the message id.
  155.     '''
  156.     timeval = time.time()
  157.     utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
  158.     pid = os.getpid()
  159.     randint = random.randrange(100000)
  160.     if idstring is None:
  161.         idstring = ''
  162.     else:
  163.         idstring = '.' + idstring
  164.     idhost = socket.getfqdn()
  165.     msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
  166.     return msgid
  167.  
  168.  
  169. def parsedate(data):
  170.     if not data:
  171.         return None
  172.     return _parsedate(data)
  173.  
  174.  
  175. def parsedate_tz(data):
  176.     if not data:
  177.         return None
  178.     return _parsedate_tz(data)
  179.  
  180.  
  181. def parseaddr(addr):
  182.     addrs = _AddressList(addr).addresslist
  183.     if not addrs:
  184.         return ('', '')
  185.     return addrs[0]
  186.  
  187.  
  188. def unquote(str):
  189.     '''Remove quotes from a string.'''
  190.     return str
  191.  
  192.  
  193. def decode_rfc2231(s):
  194.     '''Decode string according to RFC 2231'''
  195.     parts = s.split(TICK, 2)
  196.     if len(parts) <= 2:
  197.         return (None, None, s)
  198.     return parts
  199.  
  200.  
  201. def encode_rfc2231(s, charset = None, language = None):
  202.     '''Encode string according to RFC 2231.
  203.  
  204.     If neither charset nor language is given, then s is returned as-is.  If
  205.     charset is given but not language, the string is encoded using the empty
  206.     string for language.
  207.     '''
  208.     import urllib as urllib
  209.     s = urllib.quote(s, safe = '')
  210.     if charset is None and language is None:
  211.         return s
  212.     if language is None:
  213.         language = ''
  214.     
  215.     return "%s'%s'%s" % (charset, language, s)
  216.  
  217. rfc2231_continuation = re.compile('^(?P<name>\\w+)\\*((?P<num>[0-9]+)\\*?)?$')
  218.  
  219. def decode_params(params):
  220.     '''Decode parameters list according to RFC 2231.
  221.  
  222.     params is a sequence of 2-tuples containing (param name, string value).
  223.     '''
  224.     params = params[:]
  225.     new_params = []
  226.     rfc2231_params = { }
  227.     (name, value) = params.pop(0)
  228.     new_params.append((name, value))
  229.     while params:
  230.         (name, value) = params.pop(0)
  231.         if name.endswith('*'):
  232.             encoded = True
  233.         else:
  234.             encoded = False
  235.         value = unquote(value)
  236.         mo = rfc2231_continuation.match(name)
  237.         if mo:
  238.             (name, num) = mo.group('name', 'num')
  239.             if num is not None:
  240.                 num = int(num)
  241.             
  242.             rfc2231_params.setdefault(name, []).append((num, value, encoded))
  243.             continue
  244.         new_params.append((name, '"%s"' % quote(value)))
  245.     if rfc2231_params:
  246.         for name, continuations in rfc2231_params.items():
  247.             value = []
  248.             extended = False
  249.             continuations.sort()
  250.             for num, s, encoded in continuations:
  251.                 if encoded:
  252.                     s = urllib.unquote(s)
  253.                     extended = True
  254.                 
  255.                 value.append(s)
  256.             
  257.             value = quote(EMPTYSTRING.join(value))
  258.             if extended:
  259.                 (charset, language, value) = decode_rfc2231(value)
  260.                 new_params.append((name, (charset, language, '"%s"' % value)))
  261.                 continue
  262.             new_params.append((name, '"%s"' % value))
  263.         
  264.     
  265.     return new_params
  266.  
  267.  
  268. def collapse_rfc2231_value(value, errors = 'replace', fallback_charset = 'us-ascii'):
  269.     if isinstance(value, tuple):
  270.         rawval = unquote(value[2])
  271.         if not value[0]:
  272.             pass
  273.         charset = 'us-ascii'
  274.         
  275.         try:
  276.             return unicode(rawval, charset, errors)
  277.         except LookupError:
  278.             return unicode(rawval, fallback_charset, errors)
  279.         
  280.  
  281.     None<EXCEPTION MATCH>LookupError
  282.     return unquote(value)
  283.  
  284.